﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;
using TBM.Core;
using TBM.Filters;
using TBM.UEditor;
using System.Text;
using System.Net.Mail;

namespace TBM.Controllers
{
    /// <summary>
    /// API接口
    /// </summary>
    public class CController : Controller
    {
        SqlConnection conn = new SqlConnection(TBM.Core.Config.ConnectionString);
        
        public CController()
        {
            conn.Open();
        }

        protected override void Dispose(bool disposing)
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

            base.Dispose(disposing);
        }


        /// <summary>
        /// 验证登陆
        /// </summary>
        /// <param name="username">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(string username, string password, bool remember)
        {
            TBM.Models.ExecuteResult result = new Models.ExecuteResult
            {
                Result = false,
                Code = Lang.LOGIN_FAILED.Code,
                Message = Lang.LOGIN_FAILED.Message
            };
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "select [UID], Password, FirstName, LastName, PicUrl, Email, Phone, QQ, RegisterDate, IsActive, Memo, CNName from dbo.Users where [UID] = @UID and [Password] = @Password";
            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Password", SqlDbType.Char, 32);
            cmd.Parameters["@UID"].Value = username;
            cmd.Parameters["@Password"].Value = App.GetPassword(password);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    TBM.Models.User user = new Models.User
                    {
                        UID = username.Trim(),
                        Password = dr["Password"].ToString(),
                        FirstName = dr["FirstName"].ToString(),
                        LastName = dr["LastName"].ToString(),
                        PicUrl = dr["PicUrl"].ToString(),
                        Email = dr["Email"].ToString(),
                        Phone = dr["Phone"].ToString(),
                        QQ = dr["QQ"].ToString(),
                        RegisterDate = Convert.ToDateTime(dr["RegisterDate"]),
                        IsActive = (bool)dr["IsActive"],
                        Memo = dr["Memo"].ToString(),
                        CNName = (bool)dr["CNName"]
                    };

                    if (user.IsActive)
                    {
                        HttpRuntime.Cache.Insert("User", user);

                        // 添加票证信息
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UID, DateTime.Now, DateTime.Now.AddHours(3), remember, "");
                        string encryptTicket = FormsAuthentication.Encrypt(ticket);
                        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket));

                        result.Result = true;
                        result.Code = Lang.LOGIN_SUCCESS.Code;
                        result.Message = Lang.LOGIN_SUCCESS.Message;
                        result.Data = FormsAuthentication.GetRedirectUrl(user.UID, false);
                    }
                    else
                    {
                        result.Result = false;
                        result.Code = Lang.ID_LOCKED.Code;
                        result.Message = Lang.ID_LOCKED.Message;
                    }
                }
                else
                {
                    result.Result = false;
                    result.Code = Lang.ID_PWD_ERROR.Code;
                    result.Message = Lang.ID_PWD_ERROR.Message;
                }
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// UEditor处理接口
        /// </summary>
        /// <param name="action"></param>
        public void UEditorHandler()
        {
            HttpContext context = System.Web.HttpContext.Current;
            string action = TBM.Core.CommandParamType.NullOrString(Request["action"]).ToString();

            TBM.UEditor.Handler hander = null;
            switch (action)
            {
                case "config":
                    hander = new ConfigHandler(context);
                    break;
                case "uploadimage":
                    hander = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = TBM.UEditor.Config.GetStringList("imageAllowFiles"),
                        PathFormat = TBM.UEditor.Config.GetString("imagePathFormat"),
                        SizeLimit = TBM.UEditor.Config.GetInt("imageMaxSize"),
                        UploadFieldName = TBM.UEditor.Config.GetString("imageFieldName")
                    });
                    break;
                case "uploadscrawl":
                    hander = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = new string[] { ".png" },
                        PathFormat = TBM.UEditor.Config.GetString("scrawlPathFormat"),
                        SizeLimit = TBM.UEditor.Config.GetInt("scrawlMaxSize"),
                        UploadFieldName = TBM.UEditor.Config.GetString("scrawlFieldName"),
                        Base64 = true,
                        Base64Filename = "scrawl.png"
                    });
                    break;
                case "uploadvideo":
                    hander = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = TBM.UEditor.Config.GetStringList("videoAllowFiles"),
                        PathFormat = TBM.UEditor.Config.GetString("videoPathFormat"),
                        SizeLimit = TBM.UEditor.Config.GetInt("videoMaxSize"),
                        UploadFieldName = TBM.UEditor.Config.GetString("videoFieldName")
                    });
                    break;
                case "uploadfile":
                    hander = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = TBM.UEditor.Config.GetStringList("fileAllowFiles"),
                        PathFormat = TBM.UEditor.Config.GetString("filePathFormat"),
                        SizeLimit = TBM.UEditor.Config.GetInt("fileMaxSize"),
                        UploadFieldName = TBM.UEditor.Config.GetString("fileFieldName")
                    });
                    break;
                case "listimage":
                    hander = new ListFileManager(context, TBM.UEditor.Config.GetString("imageManagerListPath"), TBM.UEditor.Config.GetStringList("imageManagerAllowFiles"));
                    break;
                case "listfile":
                    hander = new ListFileManager(context, TBM.UEditor.Config.GetString("fileManagerListPath"), TBM.UEditor.Config.GetStringList("fileManagerAllowFiles"));
                    break;
                case "catchimage":
                    hander = new CrawlerHandler(context);
                    break;
                default:
                    hander = new NotSupportedHandler(context);
                    break;
            }

            hander.Process();
        }


        /// <summary>
        /// 获取联系人
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public JsonResult GetContacts(string q, int count)
        {
            JsonResult result = new JsonResult();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = @"select 
	                                top (@Count)
                                    UID, PicUrl, 
                                    case when CNName = 1 then FirstName + LastName else LastName + ' ' + FirstName end as FullName
                                from 
	                                dbo.Users 
                                where 
                                    IsActive = 1 and
	                                UID like '%' + @Query + '%' or 
	                                FirstName like '%' + @Query + '%' or 
	                                LastName like '%' + @Query + '%'
                                order by 
	                                case 
		                                when UID like @Query + '%' then 0
		                                when UID like '%' + @Query + '%' then 1
		                                when FirstName like @Query + '%' then 2
		                                when FirstName like '%' + @Query then 3
		                                when LastName like @Query + '%' then 3
		                                when LastName like '%' + @Query then 5
		                                else 6
	                                end asc, UID";
            cmd.Parameters.Add("@Query", SqlDbType.NVarChar, 50);
            cmd.Parameters.Add("@Count", SqlDbType.Int);
            cmd.Parameters["@Query"].Value = q;
            cmd.Parameters["@Count"].Value = count;

            List<Models.UserListItem> contacts = new List<Models.UserListItem>();
            Core.LangItem li = null;

            try
            {
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        contacts.Add(new Models.UserListItem
                        {
                            UID = dr["UID"].ToString(),
                            FullName = dr["FullName"].ToString(),
                            PicUrl = dr["PicUrl"] != DBNull.Value ? dr["PicUrl"].ToString() + "small.png" : Core.Config.DefaultPic
                        });
                    }
                }
                li = Core.Lang.CMD_SUCCESS;
            }
            catch
            {
                li = Core.Lang.GET_CONTACTS_FAILED;
            }


            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = contacts
            };

            return result;
        }

        public JsonResult GetUsers(string[] uids)
        {
            JsonResult result = new JsonResult();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = @"select UID, PicUrl, case when CNName = 1 then FirstName + LastName else LastName + ' ' + FirstName end as FullName 
	                                from dbo.Users as U inner join fn_Split(@UIDs, ',') as I on U.UID = I.Item";
            cmd.Parameters.Add("@UIDs", SqlDbType.VarChar, 4000);
            cmd.Parameters["@UIDs"].Value = String.Join(",", uids);

            List<Models.UserListItem> contacts = new List<Models.UserListItem>();
            Core.LangItem li = null;

            try
            {
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        contacts.Add(new Models.UserListItem
                        {
                            UID = dr["UID"].ToString(),
                            FullName = dr["FullName"].ToString(),
                            PicUrl = dr["PicUrl"] != DBNull.Value ? dr["PicUrl"].ToString() + "small.png" : Core.Config.DefaultPic
                        });
                    }
                }
                li = Core.Lang.CMD_SUCCESS;
            }
            catch
            {
                li = Core.Lang.GET_CONTACTS_FAILED;
            }


            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = contacts
            };

            return result;
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="mailaddress">邮件地址</param>
        /// <returns></returns>
        public JsonResult ForgetPassword(string mailaddress)
        {
            JsonResult result = new JsonResult(); 
            SqlCommand cmd = new SqlCommand();
            Models.ExecuteResult er = new Models.ExecuteResult();

            cmd.Connection = conn;

            cmd.CommandText = "declare @UID varchar(15); select @UID = UID from dbo.Users where Email = @Email; exec p_ResetPassword @UID, @NewPassword";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@NewPassword", SqlDbType.Char, 32);
            cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100);

            List<string> failedSendList = new List<string>();
            string bodyHTML = @"亲爱的{0}，
                                <p>　　您好！</p>
                                <p>　　您的密码已被修改为：{1}，您的UID为：{2}，请尽快登陆修改！</p>
                                <p style=""color: #ff0000;"">　　{3}系统邮件，请勿回复</p>
                                <p>{3}</p>";

            char[] newPassword = new char[8];
            Random random = new Random();

            for (int i = 0; i < newPassword.Length; i++)
            {
                newPassword[i] = (char)(97 + random.Next(26));
            }

            StringBuilder newpwd = new StringBuilder();
            newpwd.Append(newPassword);

            cmd.Parameters["@Email"].Value = mailaddress;
            cmd.Parameters["@NewPassword"].Value = Core.App.GetPassword(newpwd.ToString());

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    MailAddress address = new MailAddress(dr["Email"].ToString(), dr["FullName"].ToString(), Encoding.UTF8);
                    er = Core.App.SendEmail("您的登陆密码已被修改", String.Format(bodyHTML, address.DisplayName, newpwd, dr["UID"].ToString(), Core.Config.SMTPDisplayName), address);
                }

                dr.Close();
            }

            result.Data = er;

            return result;
        }
    }
}
